package middleware

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"mall/admin/utils"
	"log"
)

func TokenValidMiddleware() gin.HandlerFunc {

	return func(ctx *gin.Context) {
        //校驗token的合法性
		tokenStr := ctx.GetHeader("token")
		token, err := jwt.ParseWithClaims(tokenStr, &utils.MyCustomClaims{}, func(token *jwt.Token) (interface{},error) {
			return utils.SignKey, nil
		})
		if err!=nil{
			log.Println(err)
			ctx.JSON(200,utils.Fail(err))
			ctx.Abort()
			return
		}
		claims:=token.Claims.(*utils.MyCustomClaims)
		log.Printf("該用戶的id為：%s",claims.UserId)
		//TODO 將userId錄入redis，統計在線用戶
		ctx.Next()
	}

}